package com.zdlt.admin.api.controller;

import com.zdlt.admin.api.common.VueResult;
import com.zdlt.admin.api.common.util.FileUtil;
import com.zdlt.admin.api.domain.SystemUser;
import com.zdlt.admin.api.mapper.SystemUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
@CrossOrigin
@RequestMapping
@RestController
public class FileUploadController {
    //绑定文件上传路径到uploadPath
    @Value("${web.upload-path}")
    private String uploadPath;

    @Autowired
    private SystemUserMapper systemUserMapper;

    @ResponseBody
    @PatchMapping("/mp/v1_0/user/photo")
    public VueResult<String> upload(
            @RequestParam("photo") MultipartFile uploadFile,
            HttpServletRequest request) {
        // 根据token获取用户信息，校验用户信息
        SystemUser systemUser = new SystemUser();
        systemUser.setId(1L);

        try {
            String filePath = FileUtil.upload(uploadFile, request, uploadPath);
            // 根据用户id修改用户资料
            systemUser.setPhoto(filePath);
            systemUserMapper.update(1L, systemUser);

            VueResult<String> vueResult = new VueResult();
            vueResult.setMessage("OK");
            vueResult.setData(filePath);
            return vueResult;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败：" + e.getMessage());
        }
    }
}
